 

package com.zdkj.subway.rca.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.dto.in.SwCkStationDailyReportAdjustUpdateDTO;
import com.zdkj.subway.rca.dto.in.SwCkStationDailyReportQueryDTO;
import com.zdkj.subway.rca.entity.SwCkStationDailyReportAdjust;
import com.zdkj.subway.rca.entity.SwCkStationDailyReportAdjustLog;
import com.zdkj.subway.rca.entity.SwCkStationDailyReportAdjustRecordLog;
import com.zdkj.subway.rca.service.SwCkStationDailyReportAdjustLogService;
import com.zdkj.subway.rca.service.SwCkStationDailyReportAdjustRecordLogService;
import com.zdkj.subway.rca.service.SwCkStationDailyReportAdjustService;
import com.zdkj.subway.rca.service.impl.SwCkStationDailyReportAdjustServiceImpl;
import com.zdkj.subway.rca.util.MyBeanUtils;
import com.zdkj.subway.rca.util.MyDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.File;
import java.util.stream.Collectors;


/**
 * 报表调账-西安地铁日报表调账
 *
 * @author stw
 * @date 2020-10-30 15:43:30
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swckstationdailyreportadjust" )
@Api(value = "swckstationdailyreportadjust", tags = "报表调账-西安地铁日报表调账")
public class SwCkStationDailyReportAdjustController {
    //调账表
	@Autowired
    private final SwCkStationDailyReportAdjustService swCkStationDailyReportAdjustService;
    //调账表修改操作日志表
    @Autowired
    private final SwCkStationDailyReportAdjustLogService swCkStationDailyReportAdjustLogService;
    //调账表实现类
	@Autowired
    SwCkStationDailyReportAdjustServiceImpl SwCkStationDailyReportAdjustServiceImpl;
    //调账表生成日志表
	@Autowired
    private SwCkStationDailyReportAdjustRecordLogService swCkStationDailyReportAdjustRecordLogService;
    /**
     * 查询日报表
     * @param
	 *       dto
	 *      调账表查询单个日期和线路查询条件
     * @return
	 *       调账表对应线路和日期每个车站的数据
     */
    @ApiOperation(value = "查询日报表,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "查询日报表,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping("/listSwCkStationDailyReport" )
    public R listSwCkStationDailyReport(SwCkStationDailyReportQueryDTO dto) {
        /* 交易日期和线路必选
		   如果任意为空，提示
		*/
		if(StringUtils.isEmpty(dto.getTradeDate()) ||  StringUtils.isEmpty(dto.getLineCode())){
            return R.failed("日期和线路必选");
        }
        List<SwCkStationDailyReportAdjust> swCkStationDailyReportAdjusts =
                swCkStationDailyReportAdjustService.listSwCkStationDailyReportAdjust(dto);
        return R.ok(swCkStationDailyReportAdjusts);
    }

    /**
     * 查询调账日报表分页---列表页
     * @param
	 * startDate", value = "开始日期：yyyy-MM-dd"
	 * "endDate", value = "结束日期：yyyy-MM-dd"
	 * name = "lineCode", value = "线路编码"
	 * name = "confirmStatus", value = "确认状态"
     * @return
	 * 调账表列表信息
     */
    @ApiOperation(value = "查询调账日报表,tradeDate(日期) 必选,lineCode(线路) 必选,confirmStatus(确认状态)", notes = "查询调账日报表,tradeDate(日期) 必选,lineCode(线路) 必选,confirmStatus(确认状态)")
    @GetMapping("/listQuerySwCkStationDailyReport" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCode", value = "线路编码", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "confirmStatus", value = "确认状态", dataTypeClass = String.class)
            }
    )
    public R listQuerySwCkStationDailyReport(Page page,String lineCode,String confirmStatus, String startDate, String endDate) {
        SwCkStationDailyReportQueryDTO dto = new SwCkStationDailyReportQueryDTO();
        dto.setStartDate(startDate);
        dto.setEndDate(endDate);
        dto.setLineCode(lineCode);
        dto.setConfirmStatus(confirmStatus);
        return R.ok(swCkStationDailyReportAdjustService.listQuerySwCkStationDailyReportAdjust(page,dto));
    }

    /**
     * 查询调账日报表分预览---预览页面
     * @param
	 *       dto
	 *      调账表查询单个日期和线路查询条件
     * @return
	 *       调账表对应线路和日期每个车站的数据
     */
    @ApiOperation(value = "查询调账日报表分预览,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "查询调账日报表分预览,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping("/getQuerySwCkStationDailyReport" )
    public R getQuerySwCkStationDailyReport(SwCkStationDailyReportQueryDTO dto) {
       /* 交易日期和线路必选
		   如果任意为空，提示
		*/
		if(StringUtils.isEmpty(dto.getTradeDate()) ||  StringUtils.isEmpty(dto.getLineCode())){
            return R.failed("日期和线路不能为空！");
        }
        return R.ok(swCkStationDailyReportAdjustService.listSwCkStationDailyReportAdjust(dto));
    }
    /**
     * 报表调账-西安地铁收入日报表-修改日报表
     * @param swCkStationDailyReportList 
	 *              报表调账-西安地铁收入日报表
	 * catTicketPayCard 
	 *               长安通刷卡消费
	 * allOneTrafficCard
	 *               交通卡一卡通消费
     * @return R
	 *          成功或者失败
     */
    @ApiOperation(value = "修改日报表，id必选", notes = "修改日报表，id必选")
    //@SysLog("报表调账-西安地铁收入日报表-修改日报表" )
    @PutMapping({"/updateBatch"})
    @PreAuthorize("@pms.hasPermission('sw_ck_station_daily_report_edit')" )
    public R updateBatch(@RequestBody List<SwCkStationDailyReportAdjustUpdateDTO> swCkStationDailyReportList,String catTicketPayCard,String allOneTrafficCard) {
        List<SwCkStationDailyReportAdjust> listSwCkStationDailyReportAdjust = new ArrayList<>();
        List<SwCkStationDailyReportAdjustLog> listSwCkStationDailyReportAdjustLog = new ArrayList<>();
        List<SwCkStationDailyReportAdjustRecordLog> recordLogList = new ArrayList<>();
        for(SwCkStationDailyReportAdjustUpdateDTO dto : swCkStationDailyReportList){
           // 如果不存在，直接跳过
			if(dto.getId() == null){
                continue;
            }
            SwCkStationDailyReportAdjust dbSwCkStationDailyReportAdjust = this.swCkStationDailyReportAdjustService.getById(dto.getId());
            /* 20210723 去掉确认状态限制
			if ("1".equals(dbSwCkStationDailyReportAdjust.getConfirmStatus())) { //已确认不允许修改
                continue;
            }*/
           
           //解行金额  现金合计+差异  =insertObj.setSettlementAmount(totalCash + diff);
            //差异=现金缴款单-现金合计
            //现金缴款单=解行金额
            Long bankCashPaymentNote = 0L;
//            if(dbSwCkStationDailyReportAdjust.getStationTicketLongCash() > 0){
//                bankCashPaymentNote = dbSwCkStationDailyReportAdjust.getStationTicketLongCash() + dbSwCkStationDailyReportAdjust.getSettlementAmount();
//            } else if(dbSwCkStationDailyReportAdjust.getStationTicketShortCash() < 0){
//                bankCashPaymentNote = dbSwCkStationDailyReportAdjust.getSettlementAmount() - dbSwCkStationDailyReportAdjust.getStationTicketShortCash();
//            } else {
//                bankCashPaymentNote =  dbSwCkStationDailyReportAdjust.getSettlementAmount();
//            }
            
            bankCashPaymentNote =  dbSwCkStationDailyReportAdjust.getSettlementAmount();

            //修改之前的数据保存到日志表
            SwCkStationDailyReportAdjustRecordLog recordLog = new SwCkStationDailyReportAdjustRecordLog();
            BeanUtils.copyProperties(dbSwCkStationDailyReportAdjust,recordLog);
            recordLogList.add(recordLog);

            //拷贝对象
            MyBeanUtils.copyProperties(dto, dbSwCkStationDailyReportAdjust);
            /**
			 * 重新组织相应小计
			 *TVM发售小计、BOM票款小计等
			 */
            //TVM发售小计
            dbSwCkStationDailyReportAdjust.setTvmSubTotal(dbSwCkStationDailyReportAdjust.getTvmOneTicketCash() + dbSwCkStationDailyReportAdjust.getTvmOneTicketAlipay() + dbSwCkStationDailyReportAdjust.getTvmOneTicketWechat() + dbSwCkStationDailyReportAdjust.getTvmOneTicketBank());
            //BOM票款小计
            dbSwCkStationDailyReportAdjust.setBomSubTotal(dbSwCkStationDailyReportAdjust.getBomOneTicketCash() +dbSwCkStationDailyReportAdjust.getBomOnePosAmount() + dbSwCkStationDailyReportAdjust.getBomOneTicketAlipay() + dbSwCkStationDailyReportAdjust.getBomOneTicketWechat());
            //日票其他车票小计
            dbSwCkStationDailyReportAdjust.setDailySubTotal(dbSwCkStationDailyReportAdjust.getDailyTicketCash() +dbSwCkStationDailyReportAdjust.getDailyTicketPosAmount() + dbSwCkStationDailyReportAdjust.getDailyTicketAlipay() + dbSwCkStationDailyReportAdjust.getDailyTicketWechat()  + dbSwCkStationDailyReportAdjust.getDailyTicketCat());
            //纪念票小计
            dbSwCkStationDailyReportAdjust.setCommemorativeTicketSubTotal(dbSwCkStationDailyReportAdjust.getCommemorativeTicketCash() +dbSwCkStationDailyReportAdjust.getCommemorativeTicketPosAmount() + dbSwCkStationDailyReportAdjust.getCommemorativeTicketAlipay() + dbSwCkStationDailyReportAdjust. getCommemorativeTicketWechat());
            //长安通小计
            dbSwCkStationDailyReportAdjust.setCatSubTotal(dbSwCkStationDailyReportAdjust.getCatTicketCash() +dbSwCkStationDailyReportAdjust.getCatTicketPosAmount() + dbSwCkStationDailyReportAdjust.getCatTicketAlipay() + dbSwCkStationDailyReportAdjust.getCatTicketWechat()
                    + dbSwCkStationDailyReportAdjust.getCatTicketItvmAlipay() + dbSwCkStationDailyReportAdjust.getCatTicketItvmWechat() + dbSwCkStationDailyReportAdjust.getCatTicketItvmBank());
            //二维码小计
            dbSwCkStationDailyReportAdjust.setQrCodeSubTotal(dbSwCkStationDailyReportAdjust.getQrCodeTicketAlipay() + dbSwCkStationDailyReportAdjust.getQrCodeTicketWechat() + dbSwCkStationDailyReportAdjust.getQrCodeTicketUnionpay() + dbSwCkStationDailyReportAdjust.getQrCodeTicketApp()+ dbSwCkStationDailyReportAdjust.getQrCodeTicketWechatappDiscount()+ dbSwCkStationDailyReportAdjust.getQrCodeTicketWechatapp());
            //应急及互联互通小计
            dbSwCkStationDailyReportAdjust.setQrConnectivitySubTotal(dbSwCkStationDailyReportAdjust.getQrConnectivityAlipay() + dbSwCkStationDailyReportAdjust.getQrConnectivityWechat());
            //Pos小计

			dbSwCkStationDailyReportAdjust.setSubTotaPos(dbSwCkStationDailyReportAdjust.getBomOnePosAmount() +dbSwCkStationDailyReportAdjust.getPrefabricatedTicketAmount()+dbSwCkStationDailyReportAdjust.getDailyTicketPosAmount()+dbSwCkStationDailyReportAdjust.getCommemorativeTicketPosAmount()+dbSwCkStationDailyReportAdjust.getCatTicketPosAmount());
			//因为  车站票款差异（长短款）=现金缴款单—（车站营收总金额+补车站票款短款+备用金误解行）公式进行了调整，所以调整表不必再重新计算  20210922
			/*
			//现金合计
			
            Long totalCash = dbSwCkStationDailyReportAdjust.getTvmOneTicketCash() + dbSwCkStationDailyReportAdjust.getBomOneTicketCash() + dbSwCkStationDailyReportAdjust.getPrefabricatedTicketAmount()
                    + dbSwCkStationDailyReportAdjust.getEmergencyTicketAmount() + dbSwCkStationDailyReportAdjust.getTicketCounting() + dbSwCkStationDailyReportAdjust.getDailyTicketCash() + dbSwCkStationDailyReportAdjust.getCommemorativeTicketCash()
                    + dbSwCkStationDailyReportAdjust.getCatTicketCash() + dbSwCkStationDailyReportAdjust.getStationCompensation();
            //解行金额,等于现金合计
            //dbSwCkStationDailyReportAdjust.setSettlementAmount(totalCash);

            Long diff = bankCashPaymentNote - totalCash;//dbSwCkStationDailyReportAdjust.getSettlementAmount();

            if (diff  >= 0) {
                //车站票款现金长款
                dbSwCkStationDailyReportAdjust.setStationTicketLongCash(diff);
                dbSwCkStationDailyReportAdjust.setStationTicketShortCash(0L);
            } else {
                dbSwCkStationDailyReportAdjust.setStationTicketLongCash(0L);
                //车站票款现金短款
                dbSwCkStationDailyReportAdjust.setStationTicketShortCash(diff);
            }-----   20210922   */



            //收入小计
//            dbSwCkStationDailyReportAdjust.setSubTota(dbSwCkStationDailyReportAdjust.getTvmOneTicketCash() + dbSwCkStationDailyReportAdjust.getTvmOneTicketAlipay() + dbSwCkStationDailyReportAdjust.getTvmOneTicketWechat() + dbSwCkStationDailyReportAdjust.getTvmOneTicketBank() + dbSwCkStationDailyReportAdjust.getBomOneTicketCash() +
//                    dbSwCkStationDailyReportAdjust.getBomOneTicketAlipay() + dbSwCkStationDailyReportAdjust.getBomOneTicketWechat() + dbSwCkStationDailyReportAdjust.getPrefabricatedTicketAmount() + dbSwCkStationDailyReportAdjust.getEmergencyTicketAmount() + dbSwCkStationDailyReportAdjust.getTicketCounting() +
//                    dbSwCkStationDailyReportAdjust.getDailyTicketCash() + dbSwCkStationDailyReportAdjust.getDailyTicketAlipay() + dbSwCkStationDailyReportAdjust.getDailyTicketWechat() + dbSwCkStationDailyReportAdjust.getCommemorativeTicketCash() + dbSwCkStationDailyReportAdjust.getCommemorativeTicketAlipay() +
//                    dbSwCkStationDailyReportAdjust.getCommemorativeTicketWechat() + dbSwCkStationDailyReportAdjust.getAppCommemorativeTicket()  + dbSwCkStationDailyReportAdjust.getOnlineTicketSales() +
//                    dbSwCkStationDailyReportAdjust.getQrCodeTicketAlipay() + dbSwCkStationDailyReportAdjust.getQrCodeTicketWechat() + dbSwCkStationDailyReportAdjust.getQrCodeTicketUnionpay() + dbSwCkStationDailyReportAdjust.getFaceRecognitionTicketBank() +
//                    dbSwCkStationDailyReportAdjust.getStationTicketLongCash()
//            );
            //TVM小计+BOM小计+BOM配票归还POS机金额+ 预制票+应急纸票+计次票+日票小计+纪念票小计+APP纪念票+刷卡消费+网络售票+电子二维码小计+人脸+应急及互联互通小计+交通一卡通+车站票款长款
           //每个车站的收入小计重新计算
            dbSwCkStationDailyReportAdjust.setSubTota(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getTvmSubTotal())).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getBomSubTotal()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getPrefabricatedTicketAmount()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getPrefabricatedTicketPosAmount())))
                    .add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getEmergencyTicketAmount()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getTicketCounting()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getDailySubTotal())))
                    .add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getCommemorativeTicketSubTotal()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getAppCommemorativeTicket()))).add(dbSwCkStationDailyReportAdjust.getCatTicketPayCard())
                    .add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getOnlineTicketSales()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getQrCodeSubTotal()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getQrConnectivitySubTotal()))).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getFaceRecognitionTicketBank())))
                    .add(dbSwCkStationDailyReportAdjust.getAllOneTrafficCard()).add(new BigDecimal(String.valueOf(dbSwCkStationDailyReportAdjust.getStationTicketLongCash())))
            );

            PigxUser user = SecurityUtils.getUser();
            dbSwCkStationDailyReportAdjust.setUpdateName(user.getNikeName());
            dbSwCkStationDailyReportAdjust.setUpdateId(user.getId());
            dbSwCkStationDailyReportAdjust.setUpdateTime(LocalDateTime.now());
            listSwCkStationDailyReportAdjust.add(dbSwCkStationDailyReportAdjust);

            SwCkStationDailyReportAdjustLog log = new SwCkStationDailyReportAdjustLog();
            BeanUtils.copyProperties(dbSwCkStationDailyReportAdjust, log, "id");
            listSwCkStationDailyReportAdjustLog.add(log);

        }
		//日志如果存在新增
        if(!listSwCkStationDailyReportAdjustLog.isEmpty()){
            swCkStationDailyReportAdjustLogService.saveBatch(listSwCkStationDailyReportAdjustLog);
        }
        //修改之前数据保存到调账日志记录表
        if(!recordLogList.isEmpty()){
            PigxUser user = SecurityUtils.getUser();
            LocalDateTime now = LocalDateTime.now();
            //4.处理调账记录表的数据
            Map<String, List<SwCkStationDailyReportAdjustRecordLog>> collect = recordLogList.stream()
                    // 根据日期和线路进行分组
                    .collect(Collectors.groupingBy(item -> item.getTradeDate() + item.getLineCode(), Collectors.toList()));
            Set<String> keySet = collect.keySet();
            for (String key : keySet) {
                List<SwCkStationDailyReportAdjustRecordLog> swCkStationDailyReportAdjustRecordLogList = collect.get(key);
                if(CollectionUtils.isNotEmpty(swCkStationDailyReportAdjustRecordLogList)){
                    String uuid = UUID.randomUUID().toString().toLowerCase();
                    swCkStationDailyReportAdjustRecordLogList.stream().forEach(x -> {
                        x.setLogGroupId(uuid);
                        x.setLogConductorCode(user.getUserCode());
                        x.setLogConductorName(user.getNikeName());
                        x.setLogTime(now);
                    });

                }
            }
            swCkStationDailyReportAdjustRecordLogService.saveBatch(recordLogList);
        }
       //调账表数据如果不为空
	   // 进行批量修改
	   if(!listSwCkStationDailyReportAdjust.isEmpty()){
           swCkStationDailyReportAdjustService.updateBatchById(listSwCkStationDailyReportAdjust);
           //查合计
           SwCkStationDailyReportAdjust swCkStationDailyReportAdjustSum = SwCkStationDailyReportAdjustServiceImpl.getSwCkStationDailyReportAdjustSum(listSwCkStationDailyReportAdjust,catTicketPayCard,allOneTrafficCard);
           LambdaUpdateWrapper<SwCkStationDailyReportAdjust> eq = Wrappers.<SwCkStationDailyReportAdjust>lambdaUpdate()
                   .eq(SwCkStationDailyReportAdjust::getLineCode, swCkStationDailyReportAdjustSum.getLineCode())
                   .eq(SwCkStationDailyReportAdjust::getStationCode, swCkStationDailyReportAdjustSum.getStationCode())
                   .eq(SwCkStationDailyReportAdjust::getTradeDate, swCkStationDailyReportAdjustSum.getTradeDate())
                   .eq(SwCkStationDailyReportAdjust::getDelFlag, "0");
           return R.ok(swCkStationDailyReportAdjustService.update(swCkStationDailyReportAdjustSum,eq));
       } else {
           return R.failed("没有可以修改的数据");
       }

    }

    /**
     * 确认日报表
	 *          前台功能已屏蔽此功能
     * @param dto 报表调账-西安地铁收入日报表ID list
	 * tradeDate(日期) 必选,lineCode(线路) 必选
     * @return R
	 *         成功或者失败
     */
    @ApiOperation(value = "确认日报表,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "确认日报表,tradeDate(日期) 必选,lineCode(线路) 必选")
    //@SysLog("报表调账-西安地铁收入日报表-确认日报表" )
    @GetMapping({"/confirmBatch"})
    @PreAuthorize("@pms.hasPermission('sw_ck_station_daily_report_confirm')" )
    public R confirmBatch(SwCkStationDailyReportQueryDTO dto) {
        /* 交易日期和线路必选
		   如果任意为空，提示
		*/
		if(StringUtils.isEmpty(dto.getTradeDate()) ||  StringUtils.isEmpty(dto.getLineCode())){
            return R.failed("日期和线路不能为空！");
        }
        //根据日期、线路、确认状态、删除标识进行查询
		//根据查询到的数据，状态变为已确认
		LocalDate tradeDate = LocalDate.parse(dto.getTradeDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        UpdateWrapper<SwCkStationDailyReportAdjust> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("TRADE_DATE", tradeDate)
                .eq("LINE_CODE", dto.getLineCode()).eq("CONFIRM_STATUS","0").eq("DEL_FLAG","0");
        SwCkStationDailyReportAdjust swCkStationDailyReportAdjust = new SwCkStationDailyReportAdjust();
        PigxUser user = SecurityUtils.getUser();
        swCkStationDailyReportAdjust.setConfirmName(user.getNikeName());
        swCkStationDailyReportAdjust.setConfirmId(user.getId());
        swCkStationDailyReportAdjust.setConfirmTime(LocalDateTime.now());
        swCkStationDailyReportAdjust.setConfirmStatus("1");
        return R.ok(swCkStationDailyReportAdjustService.update(swCkStationDailyReportAdjust,updateWrapper));
    }

    /**
     * 导出日报表
	 * tradeDate(日期) 必选,lineCode(线路) 必选
     * @param
     * @return
     */
    @ApiOperation(value = "导出日报表,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "导出日报表,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping({"/export"})
    //@SysLog("报表调账-西安地铁收入日报表-导出日报表")
    @PreAuthorize("@pms.hasPermission('sw_ck_station_daily_report_export')")
    public void export(SwCkStationDailyReportQueryDTO dto, HttpServletResponse response) {
        /* 交易日期和线路必选
		   如果任意为空，提示
		*/
		if(StringUtils.isEmpty(dto.getTradeDate()) ||  StringUtils.isEmpty(dto.getLineCode())){
            return;
        }
        swCkStationDailyReportAdjustService.export(dto,response);
    }

    /**
     * 报表调账-西安地铁收入日报表-确认日报表（批量）
     * @param startDate   开始日期：yyyy-MM-dd
     * @param endDate     结束日期：yyyy-MM-dd
     * @param lineCodes     线路多选
     * @return
     */
    @ApiOperation(value = "确认日报表", notes = "确认日报表")
    //@SysLog("报表调账-西安地铁收入日报表-确认日报表" )
    @GetMapping({"/confirmMany"})
    @PreAuthorize("@pms.hasPermission('sw_ck_station_daily_report_confirmMany')" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCodes", value = "线路多选", dataTypeClass = String.class)
            }
    )
    public R confirmMany(String startDate, String endDate,String lineCodes) {

        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate) && StringUtils.isNotEmpty(lineCodes);
        if(isDateCondition) {
            LocalDate startDateLocalDate = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate endDateLocalDate = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            UpdateWrapper<SwCkStationDailyReportAdjust> updateWrapper=new UpdateWrapper<>();
            updateWrapper.between("TRADE_DATE", startDateLocalDate, endDateLocalDate)
                    .in("LINE_CODE", lineCodes.split(",")).eq("CONFIRM_STATUS","0").eq("DEL_FLAG","0");

            SwCkStationDailyReportAdjust swCkStationDailyReportAdjust = new SwCkStationDailyReportAdjust();
            PigxUser user = SecurityUtils.getUser();
            swCkStationDailyReportAdjust.setConfirmName(user.getNikeName());
            swCkStationDailyReportAdjust.setConfirmId(user.getId());
            swCkStationDailyReportAdjust.setConfirmTime(LocalDateTime.now());
            swCkStationDailyReportAdjust.setConfirmStatus("1");
            return R.ok(swCkStationDailyReportAdjustService.update(swCkStationDailyReportAdjust,updateWrapper));

        }
        return R.ok();
    }

    /**
     * 根据日期导出调账表--现在使用，线路多选是为了1号线二期和5号线二期合并成一条线路的情况，其他2号线等导出时用户会单选。
     * @param
	 * @param startDate   开始日期：yyyy-MM-dd
     * @param endDate     结束日期：yyyy-MM-dd
     * @param lineCodes     线路多选
     * @return
     */
    @ApiOperation(value = "根据日期导出调账表,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "根据日期导出调账表,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping({"/exportDate"})
    //@SysLog("报表调账-西安地铁调账表查询-根据日期导出调账表")
    @PreAuthorize("@pms.hasPermission('sw_ck_station_daily_report_exportDateOpen')")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCodes", value = "线路多选", dataTypeClass = String.class)
            }
    )
    public void exportDate(String startDate, String endDate,String lineCodes, HttpServletResponse response) throws ParseException {
        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate) && StringUtils.isNotEmpty(lineCodes);
        //日期条件不符合，直接返回
		if(!isDateCondition){
            return;
        }
        swCkStationDailyReportAdjustService.exportDate(startDate,endDate,lineCodes,"2",response);
    }

	   /**
     * 按财务导出（日期）调账表--现在使用，
	 *                   线路多选是为了1号线二期和5号线二期合并成一条线路的情况，其他2号线等导出时用户会单选。
     * @param startDate   开始日期：yyyy-MM-dd
     * @param endDate     结束日期：yyyy-MM-dd
     * @param lineCodes     线路多选
     * @return
     */
    @ApiOperation(value = "按财务导出（日期）调账表,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "根据日期导出调账表,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping({"/exportAffairsDate"})
    //@SysLog("报表调账-西安地铁调账表查询-根据财务导出调账表")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCodes", value = "线路多选", dataTypeClass = String.class)
            }
    )
    public void exportAffairsDate(String startDate, String endDate,String lineCodes, HttpServletResponse response) throws ParseException {
        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate) && StringUtils.isNotEmpty(lineCodes);
        if(!isDateCondition){
            return;
        }
        swCkStationDailyReportAdjustService.exportDate(startDate,endDate,lineCodes,"1",response);//按财务导出查询对账明细汇总表数据
    }

    /**
     * 根据线路导出调账表  线路多选对应有一二期合并的情况处理  --现在使用，
	 *        线路多选是为了1号线二期和5号线二期合并成一条线路的情况，其他2号线等导出时用户会单选。
     * @param startDate   开始日期：yyyy-MM-dd
     * @param endDate     结束日期：yyyy-MM-dd
     * @param lineCodes     线路多选
     * @return
     */
    @ApiOperation(value = "根据站点导出调账表,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "根据日期导出调账表,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping({"/exportStation"})
    //@SysLog("报表调账-西安地铁调账表查询-根据站点导出调账表")
    @PreAuthorize("@pms.hasPermission('sw_ck_station_daily_report_exportStationOpen')")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "startDate", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "endDate", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCodes", value = "线路多选", dataTypeClass = String.class)
            }
    )
    public void exportStation(String startDate, String endDate,String lineCodes, HttpServletResponse response) throws ParseException {
        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate) && StringUtils.isNotEmpty(lineCodes) ;
        if(!isDateCondition){
            return;
        }
        swCkStationDailyReportAdjustService.exportStation(startDate,endDate,lineCodes,"2",response);
    }

    /**
     * 报表调账-西安地铁收入日报表-确认日报表 一键确认
	 * @param tradeDateList    日期范围,中间用逗号分隔
     * @param lineCodeList     线路多选,中间用逗号分隔
     * @return
     */
    @ApiOperation(value = "报表调账-西安地铁收入日报表-确认日报表 一键确认", notes = "报表调账-西安地铁收入日报表-确认日报表 一键确认")
    //@SysLog("报表调账-西安地铁收入日报表-确认日报表 一键确认" )
    @GetMapping({"/clickConfirm"})
    @PreAuthorize("@pms.hasPermission('sw_ck_station_daily_report_clickConfirm')" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "tradeDateList", value = "开始日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCodeList", value = "结束日期：yyyy-MM-dd", dataTypeClass = String.class),
            }
    )
    @Transactional(rollbackFor = Exception.class)
    public R clickConfirm(String tradeDateList, String lineCodeList) {

        boolean isDateCondition = StringUtils.isNotEmpty(tradeDateList) && StringUtils.isNotEmpty(lineCodeList);
        String[] splitDate = tradeDateList.split(",");
        String[] splitLine = lineCodeList.split(",");
        if(isDateCondition){
            for (int i = 0; i < splitDate.length; i++) {
                LocalDate tradeDate = MyDateUtil.StringTurnLocalDate(splitDate[i]);
                UpdateWrapper<SwCkStationDailyReportAdjust> updateWrapper=new UpdateWrapper<>();
                updateWrapper.eq("TRADE_DATE", tradeDate)
                        .eq("LINE_CODE", splitLine[i]).eq("CONFIRM_STATUS","0").eq("DEL_FLAG","0");

                SwCkStationDailyReportAdjust swCkStationDailyReportAdjust = new SwCkStationDailyReportAdjust();
                PigxUser user = SecurityUtils.getUser();
                swCkStationDailyReportAdjust.setConfirmName(user.getNikeName());
                swCkStationDailyReportAdjust.setConfirmId(user.getId());
                swCkStationDailyReportAdjust.setConfirmTime(LocalDateTime.now());
                swCkStationDailyReportAdjust.setConfirmStatus("1");
                swCkStationDailyReportAdjustService.update(swCkStationDailyReportAdjust,updateWrapper);
            }
        }

        return R.ok();
    }


    /**
     * 查询调帐表创建时间列表
     * @param tradeDate    日期：yyyy-MM-dd
     * @param lineCode     线路多选
     * @return
     */
    @ApiOperation(value = "查询调帐表创建时间列表,tradeDate(日期) 必选,lineCode(线路) 必选", notes = "查询调帐表创建时间列表,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping("/getTradeDateList" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "tradeDate", value = "日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCode", value = "线路", dataTypeClass = String.class),
            }
    )
    public R getTradeDateList(String tradeDate, String lineCode) {
        List<SwCkStationDailyReportAdjustRecordLog> list = swCkStationDailyReportAdjustRecordLogService.list(Wrappers.<SwCkStationDailyReportAdjustRecordLog>lambdaQuery()
                .select(SwCkStationDailyReportAdjustRecordLog::getLogTime)
                .eq(SwCkStationDailyReportAdjustRecordLog::getTradeDate, tradeDate)
                .eq(SwCkStationDailyReportAdjustRecordLog::getLineCode, lineCode)
                .groupBy(SwCkStationDailyReportAdjustRecordLog::getLogTime)
        );
        return R.ok(list);
    }

    /**
     * 查询调帐表记录
     * @param tradeDate    日期：yyyy-MM-dd
	 * @param logTime  日志日期
     * @param lineCode     线路多选
     * @return
     */
    @ApiOperation(value = "查询调帐表记录,tradeDate(创建日期) 必选,lineCode(线路) 必选", notes = "查询调帐表记录,tradeDate(日期) 必选,lineCode(线路) 必选")
    @GetMapping("/getQuerySwCkStationDailyReportAdjustRecordLog" )
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "tradeDate", value = "交易日期：yyyy-MM-dd", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "logTime", value = "创建日期：yyyy-MM-dd HH:mm:ss", dataTypeClass = String.class),
                    @ApiImplicitParam(name = "lineCode", value = "线路", dataTypeClass = String.class),
            }
    )
    public R getQuerySwCkStationDailyReportAdjustRecordLog(String tradeDate,String logTime, String lineCode) {
        if(StringUtils.isEmpty(logTime)){
            logTime = null;
        }
        List<SwCkStationDailyReportAdjustRecordLog> list = swCkStationDailyReportAdjustRecordLogService.list(Wrappers.<SwCkStationDailyReportAdjustRecordLog>lambdaQuery()
                .eq(SwCkStationDailyReportAdjustRecordLog::getTradeDate, tradeDate)
                .eq(SwCkStationDailyReportAdjustRecordLog::getLogTime, logTime)
                .eq(SwCkStationDailyReportAdjustRecordLog::getLineCode, lineCode)
        );
        return R.ok(list);
    }

	/**
	 * 调账表批量导入
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "调账表批量导入", notes = "调账表批量导入")
    //@SysLog("调账表批量导入")
    @PostMapping("/importBatch")    
    public R importBatch(@RequestParam("file") MultipartFile file) throws Exception { 
		final File excelFile = MultipartFileToFile.multipartFileToFile(file);
        return R.ok((Object)this.swCkStationDailyReportAdjustService.saveBatchWithExcel(excelFile));
       
    }
}
